import axios from 'axios';
import { apiUrl } from '@/lib/api/config';

export interface ErrorLog {
  user_id: string;
  page_url: string;
  params: any;
  error_info: string;
  error_stack: string;
}

export const reportError = async (errorLog: ErrorLog) => {
  try {
    await axios.post(`${apiUrl}/errorLogs`, errorLog);
  } catch (error) {
    console.error('Failed to report error:', error);
  }
};

export const setupGlobalErrorHandler = () => {
  // Handle unhandled promise rejections
  window.addEventListener('unhandledrejection', (event) => {
    const error = event.reason;
    const errorLog: ErrorLog = {
      user_id: localStorage.getItem('user_id') || 'unknown',
      page_url: window.location.href,
      params: {},
      error_info: error?.message || 'Unknown error',
      error_stack: error?.stack || 'No stack trace'
    };
    
    reportError(errorLog);
    showErrorToUser(error?.message || '发生未知错误');
  });

  // Handle runtime errors
  window.onerror = (message, source, lineno, colno, error) => {
    const errorLog: ErrorLog = {
      user_id: localStorage.getItem('user_id') || 'unknown',
      page_url: window.location.href,
      params: {
        source,
        lineno,
        colno
      },
      error_info: JSON.stringify(message),
      error_stack: error?.stack || 'No stack trace'
    };
    
    reportError(errorLog);
    showErrorToUser(JSON.stringify(message));
    return true; // Prevent default error handling
  };
};

const showErrorToUser = (errorMessage: string) => {
  // Create error overlay
  const overlay = document.createElement('div');
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  `;

  const errorBox = document.createElement('div');
  errorBox.style.cssText = `
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    max-width: 80%;
    text-align: center;
  `;

  const errorText = document.createElement('p');
  errorText.textContent = `加载失败请联系管理员 - ${errorMessage}`;
  errorText.style.cssText = `
    color: #dc2626;
    margin-bottom: 15px;
  `;

  const closeButton = document.createElement('button');
  closeButton.textContent = '关闭';
  closeButton.style.cssText = `
    background-color: #ef4444;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
  `;
  closeButton.onclick = () => {
    document.body.removeChild(overlay);
  };

  errorBox.appendChild(errorText);
  errorBox.appendChild(closeButton);
  overlay.appendChild(errorBox);
  document.body.appendChild(overlay);
}; 